package doyouknow.group.CnAndZhb.config.datasource;


import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

@Configuration
@MapperScan(basePackages = AqglDataSourceConfiguration.PACKAGE, sqlSessionFactoryRef = "aqglSqlSessionFactory")
public class AqglDataSourceConfiguration {
    static final String PACKAGE = "doyouknow.group.CnAndZhb.dao.second";

    @Bean(name = "aqglDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.aqgl")
    public DruidDataSource aqglDataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setBreakAfterAcquireFailure(true);
        dataSource.setFailFast(true);
        dataSource.setConnectionErrorRetryAttempts(0);
        return dataSource;
    }

    @Bean(name = "aqglTransactionManager")
    public DataSourceTransactionManager aqglTransactionManager() {
        return new DataSourceTransactionManager(aqglDataSource());
    }

    /*
     * 多数据源时，因为关闭了SPRING BOOT的默认数据源配置，使用自定义的数据源
     * 此时配置文件中配置的路径是不会生效的，需要在定义数据源代码的时候，手动指向一下mapper.xml的位置
     */
    @Bean(name = "aqglSqlSessionFactory")
    public SqlSessionFactory aqglSqlSessionFactory() throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(aqglDataSource());
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/second/*.xml"));
        return sessionFactory.getObject();
    }
}
